package cn.tedu.weibo02.controller;

import cn.tedu.weibo02.mapper.UserMapper;
import cn.tedu.weibo02.pojo.dto.UserLoginDto;
import cn.tedu.weibo02.pojo.dto.UserRegDto;
import cn.tedu.weibo02.pojo.entity.User;
import cn.tedu.weibo02.pojo.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {

    @Autowired
    UserMapper mapper;

    @RequestMapping("/reg")
    public int reg(@RequestBody UserRegDto userRegDto){
        UserVo userVo = mapper.selectByUsername(userRegDto.getUsername());
        if (userVo!=null){
            return 2;//用户名已存在
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDto,user);
        mapper.insert(user);
        return 1;
    }

    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDto userLoginDto, HttpSession session){
        UserVo userVo = mapper.selectByUsername(userLoginDto.getUsername());
        if (userVo!=null){
            if (userVo.getPassword().equals(userLoginDto.getPassword())){
                session.setAttribute("user",userVo);
                return 1;
            }
            return 2;
        }
        return 3;
    }

    @RequestMapping("currentUser")
    public UserVo currentUser(HttpSession session){
        return (UserVo) session.getAttribute("user");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
